<?php
/*
 * 用户
 */
namespace app\home\controller;

use think\request;

class User extends Common {
    public function _initialize() {
        parent::_initialize();
        $this->request = Request::instance();
    }

    //添加或更新用户地址
    public function updateAddress() {
        if (!$this->request->isPost()) {
            $this->ajaxReturn(['code' => 0, 'msg' => '非法访问!']);
        }
        $keys = ['user_id', 'name', 'phone', 'address', 'postcode'];
        $post_data = $this->request->param();
        foreach ($keys as $key) {
            if (!isset($post_data[$key]) || !$post_data[$key]) {
                $this->ajaxReturn(['code' => 0, 'msg' => '参数错误!']);
            }
            $data[$key] = $post_data[$key];
        }
        if (isset($post_data['id']) && $post_data['id']) {
            $data['id'] = $post_data['id'];
        }
        $res = model('UserAddress')->edit($data);
        if ($res !== false) {
            $this->ajaxReturn(['code' => 1, 'msg' => '更新地址成功!']);
        } else {
            $this->ajaxReturn(['code' => 0, 'msg' => '更新地址失败!']);
        }
    }
    //获取用户地址
    public function getAddress() {
        if (!$this->request->isPost()) {
            $this->ajaxReturn(['code' => 0, 'msg' => '非法访问!']);
        }
        $user_id = $this->request->param('user_id');
        if (!$user_id) {
            $this->ajaxReturn(['code' => 0, 'msg' => '参数错误!']);
        }
        $result = model('UserAddress')->getList(['user_id' => $user_id, 'status' => 1]);
        $this->ajaxReturn($result);
    }

    public function getBankAddress()
    {
        if (!$this->request->isPost()) {
            $this->ajaxReturn(['code' => 0, 'msg' => '非法访问!']);
        }
        $user_id = $this->request->param('user_id');
        if (!$user_id) {
            $this->ajaxReturn(['code' => 0, 'msg' => '参数错误!']);
        }
        $prov_cd = input('prov_cd');
        $data = $this->postData('https://jzh.fuiou.com/jzh/regAction_ajaxCityList.action', 'prov_cd=' . $prov_cd);
        $this->ajaxReturn(['code' => 1, 'msg' => $data]);

    }

    public function postData($url, $data)
    {
        $ch = curl_init();
        $timeout = 300;
        /*curl_setopt($ch,CURLOPT_HTTPHEADER,array(
            "content-type: application/x-www-form-urlencoded; charset=UTF-8"
        ));*/
        curl_setopt($ch, CURLOPT_URL, $url);
        //curl_setopt($ch, CURLOPT_REFERER, "http://localhost");   //站点
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $handles = curl_exec($ch);

        curl_close($ch);
        return $handles;
    }



}
